#include "A_Config.h"

lv_obj_t *txt_input;
char *filebuffer;
File f_editing;

class AppTextEditor : public AppBase
{
private:
    /* data */
public:
    AppTextEditor()
    {
        name = "texteditor";
        title = "文本编辑器";
        description = "文本编辑器，可以以文本形式编辑TF卡内任何文件";
        image = "\xEF\x8C\x9C";
    }
    String param;
    lv_obj_t *kb = NULL;
    lv_obj_t *ime = NULL;
    bool isKBEnabled = false;
    bool isChineseIMEEnabled = false;
    void reCreateKB();
    void setup();
    void loop();
    void destruct();
};

static bool kb_cancel = false;
static bool kb_apply = false;
static void event_keyboard(lv_event_t *e)
{
    auto code = lv_event_get_code(e);
    switch (code)
    {
    case LV_EVENT_CANCEL:
        kb_cancel = true;
        break;
    case LV_EVENT_READY:
        kb_apply = true;
        break;
    default:
        break;
    }
}
void AppTextEditor::reCreateKB()
{
    LOCKLV();
    if (kb)
        lv_obj_del(kb);
    if (ime)
        lv_obj_del(ime);
    kb = ime = NULL;
    if (isKBEnabled)
    {
        if (isChineseIMEEnabled)
        {
            ime = lv_ime_pinyin_create(scr);
            lv_obj_set_style_text_font(ime, &lv_font_chinese_16, 0);
        }
        kb = lv_keyboard_create(scr);
        lv_obj_add_event_cb(kb, event_keyboard, LV_EVENT_ALL, NULL);
        if (isChineseIMEEnabled)
        {
            lv_ime_pinyin_set_keyboard(ime, kb);
            /*Get the cand_panel, and adjust its size and position*/
            lv_obj_t *cand_panel = lv_ime_pinyin_get_cand_panel(ime);
            lv_obj_set_size(cand_panel, LV_PCT(100), LV_PCT(10));
            lv_obj_align_to(cand_panel, kb, LV_ALIGN_OUT_TOP_MID, 0, 0);
        }
        lv_keyboard_set_textarea(kb, txt_input);
        lv_obj_set_size(txt_input, lv_pct(98), lv_pct(48));
    }
    else
    {
        lv_obj_set_size(txt_input, lv_pct(98), lv_pct(98));
    }
    UNLOCKLV();
}

void AppTextEditor::setup()
{
    if (appManager.parameter == "")
    {
        param = msgbox_string("请输入要编辑的文件名");
        if (param == "")
        {
            appManager.goBack();
            return;
        }
        param.replace('/', '_');
        param.replace('\\', '_');
        param.replace('\n', '_');
        param.replace('&', '_');
        param = "/doc/" + param;
    }
    else
    {
        param = appManager.parameter;
    }
    filebuffer = (char *)ps_malloc(40960);
    if (filebuffer == NULL)
        goto err_file;
    f_editing = SDCARD.open(param, "r");
    if (!f_editing)
    {
        f_editing = SDCARD.open(param, "w");
        if (!f_editing)
        {
            goto err_file;
        }
    }
    if (f_editing.size() > 40960)
        goto err_file;
    else
        goto ok_file;
err_file:
    full_screen_msgbox(BIG_SYMBOL_CROSS, "错误", "文件无法打开或文件超过40KB，正在退出", FULL_SCREEN_BG_CROSS);
    appManager.goBack();
    return;
ok_file:
    memset(filebuffer, 0, 40960);
    LOCKLV();
    txt_input = lv_textarea_create(scr);
    lv_obj_set_size(txt_input, lv_pct(98), lv_pct(98));
    lv_obj_align(txt_input, LV_ALIGN_TOP_MID, 0, 5);
    lv_obj_set_style_text_font(txt_input, &lv_font_chinese_16, 0);

    f_editing.readBytes(filebuffer, 40960);
    if (f_editing.size() == 0)
        lv_textarea_set_text(txt_input, "");
    else
        lv_textarea_set_text(txt_input, filebuffer);
    f_editing.close();
    UNLOCKLV();
    isKBEnabled = false;
    isChineseIMEEnabled = false;
    microKB.running = true;
    hal.DoNotSleep = true;
}

void AppTextEditor::loop()
{
    if (hal.axpShortPress)
    {
        hal.axpShortPress = false;
        menu_create();
        if (isKBEnabled == false)
            menu_add(LV_SYMBOL_KEYBOARD " 打开屏幕键盘");
        else
            menu_add(LV_SYMBOL_KEYBOARD " 关闭屏幕键盘");
        if (isChineseIMEEnabled == false)
            menu_add(LV_SYMBOL_EDIT " 打开中文输入");
        else
            menu_add(LV_SYMBOL_EDIT " 关闭中文输入");
        menu_add(LV_SYMBOL_SAVE " 保存文件");
        menu_add(LV_SYMBOL_POWER " 退出编辑器");
        switch (menu_show())
        {
        case 0:
            break;
        case 1:
            isKBEnabled = !isKBEnabled;
            reCreateKB();
            break;
        case 2:
            isChineseIMEEnabled = !isChineseIMEEnabled;
            reCreateKB();
            break;
        case 3:
        {
            f_editing = SDCARD.open(param, "w");
            if (!f_editing)
            {
                lv_toast("无法保存文件");
                break;
            }
            const char *s = lv_textarea_get_text(txt_input);
            f_editing.write((const uint8_t *)s, strlen(s));
            f_editing.close();
            lv_toast("保存成功");
            break;
        }
        case 4:
            if (msgbox_yn("是否直接退出？（我也不知道你保没保存）"))
                appManager.goBack();
            break;
        default:
            break;
        }
        hal.axpShortPress = false;
    }
    if (kb_cancel == true || kb_apply == true)
    {
        kb_cancel = kb_apply = false;
        isKBEnabled = false;
        reCreateKB();
    }
    if (microKB.available())
    {
        char c = microKB.getChar();
        if (c == microKB.DEL)
        {
            lv_textarea_del_char_forward(txt_input);
        }
        else if (c == '\b')
        {
            lv_textarea_del_char(txt_input);
        }
        else if (c == microKB.LEFT)
        {
            lv_textarea_cursor_left(txt_input);
        }
        else if (c == microKB.RIGHT)
        {
            lv_textarea_cursor_right(txt_input);
        }
        else if (c == microKB.UP)
        {
            lv_textarea_cursor_up(txt_input);
        }
        else if (c == microKB.DOWN)
        {
            lv_textarea_cursor_down(txt_input);
        }
        else if (c == microKB.ESC)
        {
            hal.axpShortPress = true;
        }
        else if (c <= 0x7f)
            lv_textarea_add_char(txt_input, c);
    }
}

void AppTextEditor::destruct()
{
    free(filebuffer);
    microKB.running = false;
    isKBEnabled = false;
    kb = ime = NULL;
    hal.DoNotSleep = false;
}

static AppTextEditor app;